package com.tencreat.mall.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.tencreat.common.core.HttpResult;
import com.tencreat.common.core.controller.BaseController;
import com.tencreat.common.core.domain.model.ReqIdParam;
import com.tencreat.common.enums.BalanceBusinessType;
import com.tencreat.common.enums.BalanceTypeEnum;
import com.tencreat.common.enums.mall.AllEnum;
import com.tencreat.common.utils.DateUtils;
import com.tencreat.common.utils.RabbitSendUtils;
import com.tencreat.domain.mall.BalanceChange;
import com.tencreat.domain.mall.MallSignIn;
import com.tencreat.domain.mall.vo.MallSignInVO;
import com.tencreat.service.mall.IBalanceChangeService;
import com.tencreat.service.mall.IMallSignInService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author tang jun liang
 * @version 1.0
 * @date 2021/9/2 16:29
 */
@Api(tags = "81-签到")
//@RestController
@RequestMapping("/api/signin")
public class MallSignInController extends BaseController {
    //@Autowired
    private IMallSignInService mallSignInService;//签到
    //@Autowired
    private IBalanceChangeService balanceChangeService;//余额变动
    //@Autowired
    private RabbitSendUtils sendUtils;

    DateTimeFormatter df = DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD_HH_MM_SS);

    @ApiOperation(value = "签到")
    @PostMapping("/signIn")
    public HttpResult signIn(@RequestBody ReqIdParam id) {

        List<String> weeks = DateUtils.getWeekByNow();
        String date = DateUtils.getDate();
        Integer ind = weeks.indexOf(date);
        Long uuid = id.getId();

        //判断今天是否签到
        BalanceChange nowSignIn = isSignIn(uuid, date, weeks);
        if (null != nowSignIn) {
            return HttpResult.error("已经签到");
        }
        //周一从头开始
        if (ind == 0) {
            insetIntegral(uuid, 1);
            return HttpResult.ok();
        }
        //判断昨天是否签到
        BalanceChange signIn = isSignIn(uuid, weeks.get(ind - 1), weeks);
        //没签到 从新开始
        if (null == signIn) {
            insetIntegral(uuid, 1);
            return HttpResult.ok();
        }
        //连续签到几次
        int num = signInList(uuid, ind, weeks);
        insetIntegral(uuid, num + 1);
        return HttpResult.ok();
    }

    @ApiOperation(value = "积分列表")
    @PostMapping("/signInList")
    public HttpResult<List<MallSignInVO>> signInList() {
        QueryWrapper<MallSignIn> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("week_num");
        List<MallSignIn> list = mallSignInService.list(wrapper);
        List<MallSignInVO> list1 = Lists.transform(list, (entity) -> {
            MallSignInVO vo = new MallSignInVO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        });

        return HttpResult.ok(list1);
    }

    @ApiOperation(value = "签到记录")
    @PostMapping("/list")
    public HttpResult<Integer> list(@RequestBody ReqIdParam id) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateUtils.YYYY_MM_DD);
        List<String> weeks = DateUtils.getWeekByNow();
        QueryWrapper<BalanceChange> integralQueryWrapper = new QueryWrapper<>();
        //integralQueryWrapper.eq("business_type", BalanceBusinessType.SIGN_IN);
        integralQueryWrapper.eq("uuid", id.getId());
        integralQueryWrapper.between("create_time", LocalDateTime.parse(weeks.get(0) + " 00:00:00", df), LocalDateTime.parse(weeks.get(6) + " 23:59:59", df));
        integralQueryWrapper.orderByAsc("create_time");
        List<BalanceChange> mallIntegral = balanceChangeService.list(integralQueryWrapper);
        if (mallIntegral.size() < 1) {
            return HttpResult.ok(0);
        }
        int num = 0;
        String format = dtf.format(mallIntegral.get(mallIntegral.size() - 1).getCreateTime());
        if (dtf.format(LocalDateTime.now()).equals(format)) {
            num = 1;
        }
        LocalDateTime now = LocalDateTime.now();
        for (int i = mallIntegral.size() - 1; i > -1; i--) {
            String createDate = dtf.format(mallIntegral.get(i).getCreateTime());
            if (dtf.format(now).equals(createDate)) {
                continue;
            }
            now = now.minusDays(1);
            if (createDate.equals(dtf.format(now))) {
                num++;
            } else {
                break;
            }
        }
        return HttpResult.ok(num);
    }

    private void insetIntegral(Long uuid, Integer num) {
        QueryWrapper<MallSignIn> wrapper = new QueryWrapper<>();
        wrapper.eq("week_num", num);
        MallSignIn signIn = mallSignInService.getOne(wrapper);
        Long integral = signIn.getIntegral();
        //sendUtils.sendBalanceMessage(uuid, BigDecimal.valueOf(integral), AllEnum.BalanceChangeTypeEnums.INCOME.getType(), BalanceBusinessType.SIGN_IN,"",System.currentTimeMillis()+"", BalanceTypeEnum.CASH_INTEGRAL);
    }


    /****
     * 在本周签到几次
     * @param uuid
     * @param date  yyyy-MM-dd
     */
    private BalanceChange isSignIn(Long uuid, String date, List<String> weeks) {
        QueryWrapper<BalanceChange> integralQueryWrapper = new QueryWrapper<>();
        //integralQueryWrapper.eq("business_type", BalanceBusinessType.SIGN_IN);
        integralQueryWrapper.eq("uuid", uuid);
        if (null != date) {
            integralQueryWrapper.apply("date_format(create_time, '%Y-%m-%d') = {0}", date);
        }
        integralQueryWrapper.between("create_time", LocalDateTime.parse(weeks.get(0) + " 00:00:00", df), LocalDateTime.parse(weeks.get(6) + " 23:59:59", df));
        balanceChangeService.getOne(integralQueryWrapper);
        BalanceChange mallIntegral = balanceChangeService.getOne(integralQueryWrapper);
        return mallIntegral;
    }

    private int signInList(Long uuid, Integer ind, List<String> weeks) {
        int num = 0;
        for (int i = ind - 1; i > -1; i--) {
            if (null != isSignIn(uuid, weeks.get(i), weeks)) {
                num++;
            }
            ;
        }
        return num;
    }

}
